using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace Q.Framework.Utility
{
    public static class FieldsOf<T>
    {
        public static String[] GetNames<R>(params Expression<Func<T, R>>[] exprs)
        {
            return exprs.Select(expr =>
            {
                return GetName(expr);
            }).ToArray();
        }

        public static String GetName<R>(Expression<Func<T, R>> expr)
        {
            return GetName(expr.Body);
        }

        public static String[] GetNames(params Expression<Func<T>>[] exprs)
        {
            return exprs.Select(expr =>
            {
                return GetName(expr);
            }).ToArray();
        }

        public static String GetName(Expression<Func<T>> expr)
        {
            return GetName(expr.Body);
        }

        private static String GetName(Expression expression)
        {
            var retorno = "";

            if (expression.NodeType == ExpressionType.New)
            {
                foreach (var item in (expression as NewExpression).Arguments)
                    retorno += item.ToString().Split('.')[1] + ",";
            }
            else
            {
                var node = expression as MemberExpression;

                if (object.ReferenceEquals(null, node))
                    throw new InvalidOperationException("Expression must be a member access");

                if (node.Expression.NodeType == ExpressionType.MemberAccess)
                    retorno += GetName(node.Expression) + ".";
                retorno += node.Member.Name;
            }

            return retorno;
        }
    }
}